package com.cn.yang.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.cn.yang.model.UserModel;
import com.cn.yang.service.UserService;
import com.cn.yang.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setCode(code);
        userModel.setPassword(password);

        String sessionCode = (String) req.getSession().getAttribute("code");
        userModel.setSessionCode(sessionCode);

        UserService userService = new UserServiceImpl();
        int result = userService.login(userModel);

        if (result==1){
            req.getSession().setAttribute("username",username);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",result);
        resp.getWriter().println(jsonObject);

    }
}
